#!/usr/bin/python3
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name:         get_cap
# Description:  
# Author:       牛泽鹏
# Date:         2019/7/1
# -------------------------------------------------------------------------------
from captcha.image import ImageCaptcha
from numpy.random import randint
from ClothingStore.settings import CAPTCHA_URL
from os.path import isdir, isfile, join
from os import mkdir
from threading import Thread, currentThread

IMAGE_OBJECT = ImageCaptcha()  # 创建常量对象


def random(size=3):
    number = randint(0, 3)
    if number == 1:
        s = str(chr(randint(65, 91)))
    elif number == 2:
        s = str(chr(randint(97, 123)))
    else:
        s = str(randint(0, 10))
    return s + random(size-1) if size else s


def mk_dir():
    if not isdir(CAPTCHA_URL):  # 判断缓存文件是否存在
        mkdir(CAPTCHA_URL)  # 创建缓存文件夹


def get_image():
    mk_dir()
    global IMAGE_OBJECT
    rand_str_number = random()  # 获取随机字符串
    im_path = join(CAPTCHA_URL, rand_str_number + '.png')  # 构建文件路径
    if not isfile(im_path):  # 判断是否存在缓存
        IMAGE_OBJECT.write(rand_str_number, im_path)  # 不存在下创建图片
    return rand_str_number.lower(), im_path  # 返回(字符串(全小写判断), 图片地址)


class MakeImage:
    def __init__(self):
        self.max_number = 99999
        mk_dir()

    def run(self, number=5):
        for i in range(number):
            Thread(target=self.mk_all_img).start()

    def mk_all_img(self):
        """一次性创造出大量验证图片,节省后续CPU占用"""
        while self.max_number:
            rand_str_number = random()  # 获取随机字符串
            im_path = join(CAPTCHA_URL, rand_str_number + '.png')  # 构建文件路径
            if not isfile(im_path):
                IMAGE_OBJECT.write(rand_str_number, im_path)  # 不存在下创建图片
                self.max_number -= 1
                print('创建:', im_path, '\t剩余:', self.max_number, currentThread().name)


if __name__ == '__main__':
    # s = MakeImage()
    # s.run()
    print(get_image())
